import AppUI from './ui'
class Controller {
    constructor() {
        this.file_input = null
        //加载UI
        this.ui = new AppUI(() => {
            this.cc = document.querySelector('#canvas');
            this.ps = new window.CanvasPs(this.cc);
            this.ct = this.ps.Context;
            this.init()
        }, this);
    }


    //初始化
    init() {
        document.onkeyup = (e) => {
            if (e.keyCode == 32) {
                this.cc.style.cursor = "default";
                this.ps.setMode(0);
            }
        }
        //打开文件
        this.file_input = document.createElement('input');
        this.file_input.type = "file";

        this.file_input.onchange = ()=> {
            if (this.file_input.files[0]) {
                const file = this.file_input.files[0];
                if (file.type.search('image/') != (-1)) {
                    this.ps.openFile(file);
                } else {
                    this.ui.alert("文件不是图片");
                }
            }

        }
        //鼠标滚动缩放
        this.cc.onwheel = (e)=> {
            e.preventDefault();
            var input_sc = document.querySelectorAll('.menu input')[2];
            var num = parseInt(input_sc.value);

            if (e.wheelDelta > 0) {
                input_sc.value = num + 5;
                if (input_sc.value > 600) {
                    input_sc.value = 600;
                }
            } else {
                input_sc.value = num - 5;
                if (input_sc.value < 5) {
                    input_sc.value = 5;
                }
            }
            const scale = input_sc.value
            this.ps.scaleCanvas(scale);
        }
        //裁剪工具
        if (document.querySelectorAll('.canvas-ps-warp').length > 0) {
            document.querySelectorAll('.canvas-ps-warp')[0].style.position = 'relative';
            const box = this.ps.config.elements.cutBox
            box.className = 'pscut-box';
            box.title = '双击确定';
            document.querySelectorAll('.canvas-ps-warp')[0].appendChild(box);
            
            box.onmouseup = (e)=> {
                this.ps.config.mouse.status = 1;
                this.ps.config.mouse.cutBox.status = 1;
            }
            box.onmousedown = (e)=> {
                if ((e.offsetY > this.cc.offsetHeight - 12) || (e.offsetX > box.offsetWidth - 12)) {
                    this.ps.config.mouse.cutBox.status = 3;
                } else {
                    this.ps.config.mouse.cutBox.status = 0;
                }
                this.ps.config.mouse.cutBox.down.x = e.pageX - box.offsetLeft;
                this.ps.config.mouse.cutBox.down.y = e.pageY - box.offsetTop;
                this.ps.config.mouse.cutBox.down.ox = e.offsetX;
                this.ps.config.mouse.cutBox.down.oy = e.offsetY;
            }
            box.onmousemove = (e)=> {
                this.ps.mouseWork.moveCuttingBox(e.pageX - this.ps.config.mouse.cutBox.down.x, e.pageY - this.ps.config.mouse.cutBox.down.y);
            }
            // 调整裁剪框大小
            box.onclick = (e)=> {
                if (e.offsetX < 80 && e.offsetY < 0) {
                    //宽度
                    var nw;
                    var nh;
                    if (e.offsetX > 14 && e.offsetX < 26) {
                        nw = box.offsetWidth - 6;
                        box.style.width = nw + 'px';
                    } else if (e.offsetX > 28 && e.offsetX < 32) {
                        nw = box.offsetWidth + 6;
                        box.style.width = nw + 'px';
                    }
                    // 高度
                    else if (e.offsetX > 54 && e.offsetX < 68) {
                        nh = box.offsetHeight - 6;
                        box.style.height = nh + 'px';
                    } else if (e.offsetX > 68 && e.offsetX < 80) {
                        nh = box.offsetHeight + 6;
                        box.style.height = nh + 'px';
                    }
                }
            }
            //确定裁剪
            box.ondblclick = (e)=> {
                if (e.offsetX < 80 && e.offsetY < 0) {
                    return;
                }
                var rx = box.offsetLeft / (this.ps.config.canvas.scale / 100) - parseInt(this.ps.c.style.left) / (this.ps.config.canvas.scale / 100);
                var ry = box.offsetTop / (this.ps.config.canvas.scale / 100) - parseInt(this.ps.c.style.top) / (this.ps.config.canvas.scale / 100);
                var rw = box.offsetWidth / (this.ps.config.canvas.scale / 100);
                var rh = box.offsetHeight / (this.ps.config.canvas.scale / 100);
                this.ps.imgCutting(rx, ry, rw, rh);
                this.ps.scaleCanvas(this.ps.config.canvas.scale);
                this.ps.upData();
                this.ps.addHistory({ title: '裁剪', data: this.ps.data })
                //恢复裁剪框
                this.ps.showCuttingBox(false);
                // console.log(rx,ry);
            }
        } else {
            console.log('必须在 canvas-ps-warp 类名下直接子元素 与canvas同级的块元素才可正常使用裁剪');
        }
        //自动刷新历史
        this.refreshHistory()
    }
    openfile() {
        this.file_input.click();
    }

    //刷新操作历史
    refreshHistory() {
        const history = this.ps.getHistory();
        const historybox = document.querySelector('.history>div');
        historybox.innerHTML = null;
        for (var i = 0; i < history.length; i++) {
            var ea = document.createElement('a');
            ea.innerHTML = history[i].title;
            ea.href = 'javascript:canvaspsGo(' + i + ');'
            ea.setAttribute('data-index', i);
            historybox.appendChild(ea);
        }
        setTimeout(this.refreshHistory.bind(this), 800);
    }
    //弹出颜色调节
    opencolorwindow() {
        var r_input = document.querySelector('#color_r');
        var g_input = document.querySelector('#color_g');
        var b_input = document.querySelector('#color_b');
        var a_input = document.querySelector('#color_a');
        // console.log(ps.getColor())
        var color_str = this.ps.getColor();
        color_str = color_str.replace(/[rgba\(\)]/g, '');
        var color = color_str.split(',');
        r_input.value = color[0];
        g_input.value = color[1];
        b_input.value = color[2];
        a_input.value = color[3];
        this.ui.openwindow(1, '', '', ()=> {
            var color = [parseInt(r_input.value), parseInt(g_input.value), parseInt(b_input.value), parseInt(a_input.value * 255)];
            this.ps.colorControl(color);
            this.ps.setColor('rgba(' + r_input.value + ',' + g_input.value + ',' + b_input.value + ',' + a_input.value + ')');
            var show_color_box = document.querySelector('.color_selector');
            show_color_box.style.backgroundColor = this.ps.getColor();
        });
        this.ui.toolmsg('颜色调节');
    }
    //弹出颜色选择器
    selectcolor(el) {
        var r_input = document.querySelector('#color_r');
        var g_input = document.querySelector('#color_g');
        var b_input = document.querySelector('#color_b');
        var a_input = document.querySelector('#color_a');
        var color_str = this.ps.getColor();
        color_str = color_str.replace(/[rgba\(\)]/g, '');
        var color = color_str.split(',');
        r_input.value = color[0];
        g_input.value = color[1];
        b_input.value = color[2];
        a_input.value = color[3];
        this.ui.openwindow(1, '', '', ()=> {
            this.ps.setColor('rgba(' + r_input.value + ',' + g_input.value + ',' + b_input.value + ',' + a_input.value + ')');
            el.style.backgroundColor = this.ps.getColor();
            var show_color_box = document.querySelector('.color_selector');
            show_color_box.style.backgroundColor = this.ps.getColor();
        });
        this.ui.toolmsg('颜色选择');
    }
    //获取 调色器 颜色
    getcolor(type) {
        var r_input = document.querySelector('#color_r');
        var g_input = document.querySelector('#color_g');
        var b_input = document.querySelector('#color_b');
        var a_input = document.querySelector('#color_a');
        if (type && type == 1) {
            return 'rgba(' + r_input.value + ',' + g_input.value + ',' + b_input.value + ',' + a_input.value + ')';
        } else {
            return [r_input.value, g_input.value, b_input.value, a_input.value];
        }

    }
    //颜色调节函数
    editcolor() {

    }
    //颜色转化
    hex2Rgb(hex) {
        //十六进制转为RGB  
        var rgb = [];
        // 定义rgb数组  
        if (/^\#[0-9A-F]{3}$/i.test(hex)) {
            //判断传入是否为#三位十六进制数   
            let sixHex = '#';
            hex.replace(/[0-9A-F]/ig, (kw)=> {
                s
                ixHex += kw + kw; //把三位16进制数转化为六位   
            });
            hex = sixHex; //保存回hex  
        }
        if (/^#[0-9A-F]{6}$/i.test(hex)) {
            //判断传入是否为#六位十六进制数   
            hex.replace(/[0-9A-F]{2}/ig, (kw)=> {
                rgb.push(eval('0x' + kw)); //十六进制转化为十进制并存如数组   
            });
            return rgb; //输出RGB格式颜色  
        } else {
            // console.log(`Input ${hex} is wrong!`);   
            return [0, 0, 0];
        }
    }
    //清楚菜单样式
    clearMenuStyle() {
        var menubtn = document.querySelectorAll('.menubtn');
        for (var i = 0; i < menubtn.length; i++) {
            menubtn[i].style.backgroundColor = null;
        }
    }
    //画布跳转指定历史
    canvaspsGo(index) {
        this.ps.goto(index);
    }

    //开启 橡皮擦
    startclaer(el) {
        if (this.ps.getMode() == 3) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;

        } else {
            this.ps.stopAnimate()
            this.ps.setMode(3);
           this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('擦除模式');
        }
    }
    //开启 移动画布
    movecanvas(el) {
        if (this.ps.getMode() == 6) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;
            // c.style.cursor="default";
        } else {
            this.ps.setMode(6);
            // c.style.cursor="move";
            this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('移动画布');
        }
    }
    //开启 裁剪
    startcut(el) {
        if (this.ps.getMode() == 4) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;
            this.cc.style.cursor = "default";

        } else {
            this.ps.stopAnimate()
            this.ps.setMode(4);
            this.cc.style.cursor = "crosshair";
            this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('裁剪画布');
        }
    }
    //填充颜色
    fillcolor() {
        this.ps.setMode(8);
        this.ps.fillSelect();
    }
    //开启 多边形 选择
    startpolygon(el) {
        if (this.ps.getMode() == 11) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;
        } else {
            this.ps.stopAnimate()
            this.ps.setMode(11, this.clearMenuStyle);
            this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('多边形选择');
        }
    }
    //开启 涂鸦
    startdraw(el) {
        if (this.ps.getMode() == 2) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;

        } else {
            this.ps.stopAnimate()
            this.ps.setMode(2);
            this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('笔刷模式');
        }
    }
    //开启 铅笔
    startpencil(el) {
        if (this.ps.getMode() == 9) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;

        } else {
            this.ps.stopAnimate()
            this.ps.setMode(9);
            this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('铅笔模式');
        }
    }
    //开启 铅笔抠图
    pencut(el) {
        if (this.ps.getMode() == 10) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;
        } else {
            this.ps.stopAnimate()
            this.ps.setMode(10);
            this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('铅笔抠图');
        }
    }
    //删除选区
    del_select() {
        this.clearMenuStyle();
        this.ps.clearSelect();
    }
    //重置画布
    resetcavans() {
        this.clearMenuStyle();
        this.ps.reMake();
    }
    //缩放画布
    scalecavans(el) {
        this.ui.ps.pen.scale = el.value;
        this.ps.scaleCanvas(el.value);
        this.ui.toolmsg('缩放画布');
    }
    //画笔颜色
    changecolor(el) {
        this.ps.setColor(el.value);
        el.title = el.value;
    }
    //取消选择
    cancel() {
        this.clearMenuStyle();
        this.ps.stopAnimate()
    }
    //设置容差
    settolerance(el) {
        this.ps.setAlw(el.value);
        el.title = el.value;
    }
    //画笔大小
    setpensize(el) {
        this.ps.setWidth(el.value);
        el.title = el.value;
    }
    //拾色器
    pickercolor(el) {
        var show_color_box = document.querySelector('.color_selector');
        if (this.ps.getMode() == 12) {
            this.ps.setMode(0);
            el.style.backgroundColor = null;
        } else {
            this.ps.pickercallback = (end)=> {
                if (end) {
                    this.ps.setMode(0);
                    this.clearMenuStyle();
                } else {
                    show_color_box.style.backgroundColor = this.ps.getColor();
                    // console.log(ps.getColor())
                }
            }
            this.ps.stopAnimate()
            this.ps.setMode(12);
            this.clearMenuStyle();
            el.style.backgroundColor = "#B2B2B2";
            this.ui.toolmsg('拾色器');
        }
    }

    // 拖放文件
    dropFile(e) {
        e.preventDefault();
        if (e.dataTransfer.files[0]) {
            var file = e.dataTransfer.files[0];
            if (file.type.search('image/') != (-1)) {
                this.ps.openFile(file);
            } else {
                this.ui.alert("文件不是图片");
            }
        }
    }
    allowDrop(event) {
        event.preventDefault();
    }

    //保存
    svaeimg() {
        this.ui.openwindow(2,'选择保存类型','',()=>{
            this.save_file()
        })
    }
    //保存文件函数--------s
    save_file() {
        var img_type;//图片格式
        var type_input = document.querySelectorAll(".contr_save_type input");
        var gre_input = document.querySelector(".contr_save_gre input");
        if (type_input[0].checked) {
            img_type = "jpeg";
        } else if (type_input[1].checked) {
            img_type = "png";
        } else {
            img_type = "bmp";
        }

        let gre = gre_input.value / 10

        if (img_type == "jpeg") {
            this.ct.putImageData(this.ps.save_jpg(), 0, 0);//处理空白像素
        }
        var dataurl = this.cc.toDataURL("image/" + img_type, gre);
        var b = this.dataURLtoBlob(dataurl);
        var img_a = document.createElement("a");
        img_a.download = "new_img." + img_type;
        img_a.href = URL.createObjectURL(b);
        img_a.click();
        //恢复数据
        // ct.putImageData(ps.get_save(), 0, 0);
    }
    //保存到可下载文件
    dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }
    //查看帮助
    helper() {
        this.ui.alert('双击进入抠图选区,支持裁剪,简单调色,按住空格,鼠标可以拖到画布.可导出多种格式,简单方便!<p>这个版本不再支持移动端！<br>拾色器按下鼠标移动取色，单机右键结束！<p>');
    }
}

//创建应用
window.controller = new Controller()